import psutil
from datetime import datetime


class Computer():
    '''模型类，用于获取数据'''
    
    # cpu占用率为类的成员，没有self
    # 字典类型，key为时间，value为占用率
    cpu_percents = {}

    @classmethod
    def cpu(cls) -> dict:
        '''每执行一次获取一个实时比例值，最多不超过10个'''

        # 可读字符串表示的当地时间
        now = datetime.now().strftime('%H:%M:%S')
        cls.cpu_percents[now] = psutil.cpu_percent(interval=1)

        # CPU占用率，保持时间最近的10个值
        if len(cpu_keys := cls.cpu_percents.keys()) > 10:
            cls.cpu_percents.pop(list(cpu_keys)[0])

        return cls.cpu_percents

    @staticmethod
    def memory() -> tuple:
        # 系统当前时间
        time_stamp = datetime.now().strftime('%H:%M:%S %p %Y-%m-%d(%a)')

        # 内存大小
        memo = psutil.virtual_memory()
        # 单位为kb，换算成G
        memo_total = round(memo.total / 1024 / 1024 / 1024)
        memo_used = round(memo.used / 1024 / 1024 / 1024, 1)
        memo_available = round(memo.available / 1024 / 1024 / 1024, 1)
        memo_percent = memo.percent

        return time_stamp, memo_total, memo_used, memo_available, memo_percent


if __name__ == "__main__":
    # 测试CPU占用率
    # for i in range(10):
    #     print(Computer.cpu())

    # 测试内存使用情况
    print(Computer.memory())
